package db

import (
	mydb "filestore-rebuild/db/mysql"
	"fmt"
	"log"
)

func CheckUsernameExists(username string) bool {
	sqlStr := `select * from tbl_user where user_name = ? limit 1`
	stmt, err := mydb.DBConn().Prepare(sqlStr)
	if err != nil {
		log.Printf("Prepare statement error: %s\n", err.Error())
		return false
	}
	defer stmt.Close()
	rows, err := stmt.Query(username)
	if err != nil {
		fmt.Println(err.Error())
		return false
	} else if rows == nil {
		return true
	}
	return false
}

func UserSignup(username, password string) bool {
	sqlStr := `insert into tbl_user (user_name, user_pwd, status) values (?,?,?);`
	stmt, err := mydb.DBConn().Prepare(sqlStr)
	if err != nil {
		log.Printf("Prepare statement error: %s\n", err.Error())
		return false
	}
	defer stmt.Close()
	ret, err := stmt.Exec(username, password, 0)
	if err != nil {
		log.Printf("sql exec error: %s\n", err.Error())
		return false
	}
	if affected, err := ret.RowsAffected(); nil == err && affected > 0 {
		return true
	}
	return false
}

func UserLogin(username, password string) bool {
	stmt, err := mydb.DBConn().Prepare("select * from tbl_user where user_name=? limit 1")
	if err != nil {
		log.Println(err.Error())
		return false
	}
	defer stmt.Close()
	rows, err := stmt.Query(username)
	if err != nil {
		fmt.Println(err.Error())
		return false
	} else if rows == nil {
		fmt.Println("username not found:", username)
		return false
	}
	pRows := mydb.ParseRows(rows)
	if len(pRows) > 0 && string(pRows[0]["user_pwd"].([]byte)) == password {
		return true
	}
	return false
}

type UserInfo struct {
	Username     string
	Email        string
	Phone        string
	SignupAt     string
	LastActiveAt string
	Status       int
}

func GetUserInfo(username string) (UserInfo, error) {
	user := UserInfo{}
	stmt, err := mydb.DBConn().Prepare(
		"select user_name, email, phone, signup_at, last_active, status from tbl_user where user_name=? limit 1")
	if err != nil {
		log.Println(err.Error())
		return user, err
	}
	defer stmt.Close()
	err = stmt.QueryRow(username).Scan(&user.Username, &user.Email, &user.Phone, &user.SignupAt, &user.LastActiveAt, &user.Status)
	if err != nil {
		log.Println(err.Error())
		return user, err
	}
	return user, nil
}
